﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Text;

using Newtonsoft.Json;

namespace CommandExecutor
{
	public class RCClient
    {
		String host;
		
		public RCClient(String host)
		{
			this.host = host;
		}
		
        public TResult ExecuteCommand<T, TResult>(string command, T parameter)
        {
                TcpClient tcpclnt = new TcpClient();
                tcpclnt.Connect(host, 8001);

                Stream stm = tcpclnt.GetStream();

                var c = new Command {CommandName = command, Parameter = JsonConvert.SerializeObject(parameter)};

                byte[] ba = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(c));

                stm.Write(ba, 0, ba.Length);

                var bb = new byte[1024];
                int length = stm.Read(bb, 0, 1024);

                tcpclnt.Close();
                var resAsString = Encoding.UTF8.GetString(bb, 0, length);
                
                var resultCommand = JsonConvert.DeserializeObject<ResultCommand>(resAsString);

                if (!resultCommand.Success)
                {
                	throw new RemoteException(resultCommand.ErrorMessage, resultCommand.ErrorStackTrace);
                }
                	
                return JsonConvert.DeserializeObject<TResult>(resultCommand.Result);


            
        }
    }
}
